package com.qili.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qili.annotation.TokenCheck;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.FileDTO;
import com.qili.entity.base.BaseDict;
import com.qili.entity.jc.JcProject;
import com.qili.entity.jc.JcProjectMilepost;
import com.qili.entity.jc.JcProjectStage;
import com.qili.entity.jc.ProjectBcUnit;
import com.qili.entity.jc.dto.*;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.ProjectLeaderDTO;
import com.qili.entity.supervisor.dto.ProjectUnitConstructionDTO;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysRoleUserDTO;
import com.qili.entity.zx.ZxProject;
import com.qili.entity.zx.ZxProjectMilepost;
import com.qili.entity.zx.ZxProjectStage;
import com.qili.entity.zx.dto.ZxProjectDTO;
import com.qili.entity.zx.dto.ZxProjectMilepostDTO;
import com.qili.entity.zx.dto.ZxProjectPayDTO;
import com.qili.entity.zx.dto.ZxProjectStageDTO;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyOwnerService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.jc.*;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.sys.SysRegionService;
import com.qili.service.zx.*;
import com.qili.util.*;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;

import static java.util.Objects.isNull;

/**
 * @author zhaoyongke
 * @date 2021/10/14
 * @description
 */

@Controller
@Slf4j
@RequestMapping("/app/jc")
public class AppJcController {


    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    BaseCompanyOwnerService baseCompanyOwnerService;
    @Autowired
    JcProjectService jcProjectService;
    @Autowired
    ProjectContractService projectContractService;
    @Autowired
    ProjectLeaderService projectLeaderService;

    @Autowired
    JcProjectStageService jcProjectStageService;

    @Autowired
    JcProjectMilepostService jcProjectMilepostService;

    @Autowired
    JcProjectPayService jcProjectPayService;

    @Autowired
    ProjectPlaceService projectPlaceService;
    @Autowired
    ProjectUnitConstructionService projectUnitConstructionService;

    @Autowired
    UploadUtil uploadUtil;

    @Autowired
    SupervisorProjectFormsService supervisorProjectFormsService;
    @Autowired
    SupervisorProjectFormsDataService supervisorProjectFormsDataService;
    @Autowired
    ProjectSealRecordService projectSealRecordService;
    @Autowired
    ProjectBigEventService projectBigEventService;
    @Autowired
    JcProjectModifiedRecordService modifiedRecordService;
    @Autowired
    JcPayRecordService jcPayRecordService;
    @Autowired
    ProjectBcUnitService projectBcUnitService;
    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    BaseCompanyService baseCompanyService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProjectAdminService  projectAdminService;

    @Value("${supervisor.downloadPath}")
    private String uploadPath;
    @Value("${supervisor.tempPath}")
    private String tempPath;


    /**
     * @param project
     * @Author:Zhangshuo
     * @Description:项目管理----项目列表
     * @Date:9:47 2020-12-12
     */
    @ApiOperation(value = "/showProjectList", httpMethod = "GET", notes = "展示项目")
    @PostMapping(value = "showProjectList")
    @ResponseBody
    @TokenCheck
    public JsonUtil showProjectList(@RequestBody JcProjectDTO project) {
        String userId = project.getUserId();
        if(StringUtils.isBlank(userId)){
            return JsonUtil.error("参数获取失败");
        }
        // (1) 业主单位 （2） 承建单位  查询自己参与的项目
        //（3） 项目经理  查询自己创建的和自己参与的
        //（4） 监理工程师 （5）技术负责人 查询自己参与的项目
        //（6） 市场人员  发布的
        // (7) 管理员 公司高层 工程部经理 质控 查看全部
        // 2021 0708 添加咨询部门经理  查看全部
        //查询不是删除状态的项目
        project.setDestatus("000");
        project.setUserId(userId);
        project.setField(humpToUnderline(project.getField()));
        //判断是否是管理员  公司高层  工程部经理  质控  :
        SysRoleUserDTO sysRoleUserDTO=new SysRoleUserDTO();
        sysRoleUserDTO.setUserId(userId);
        List<SysRoleUserDTO> ListsysRoleUserDTOS = sysUserService.selectRoleUserByUser(sysRoleUserDTO);
        if(ListsysRoleUserDTOS!=null){
            if(ListsysRoleUserDTOS.size()>0){
                for (int i = 0; i <ListsysRoleUserDTOS.size() ; i++) {
                    SysRoleUserDTO sysRoleUserDTO1 = ListsysRoleUserDTOS.get(i);
                    String roleName = sysRoleUserDTO1.getRoleName();
                    if ("admin".equals(roleName) || "gsgc".equals(roleName) ||"gcbjl".equals(roleName)  || "zkjsry".equals(roleName)  || "deptcheckpersonjc".equals(roleName)  ) {
                        project.setUserId(null);
                        break;
                    }
                }
            }

        }
//        Subject subject = SecurityUtils.getSubject();
//        if (subject.hasRole("admin") || subject.hasRole("gsgc") || subject.hasRole("gcbjl") || subject.hasRole("zkjsry") || subject.hasRole("deptcheckpersonzx") ) {
//            project.setUserId(null);
//        }
        List<JcProjectDTO> jcProjectDTOS = jcProjectService.selectJcListApp(project);
        return JsonUtil.sucessWithData("返回列表成功", jcProjectDTOS);
    }


    // 项目里程碑
    @ApiOperation(value = "/selectJcMilepost", httpMethod = "GET", notes = "APP项目里程碑")
    @GetMapping(value = "selectJcMilepost")
    @ResponseBody
    @TokenCheck
    public JsonUtil selectJcMilepost(String id, String stage_id) {

        try {
            if(StringUtil.isBlank(id)  || StringUtil.isBlank(stage_id)  ){
                return JsonUtil.error("获取参数失败");
            }
            JcProjectMilepostDTO su = new JcProjectMilepostDTO();
            su.setProjectId(id);
            su.setSupervisorProjectStageId(stage_id);
            List<JcProjectMilepostDTO> AlistMilePost = jcProjectMilepostService.selectProjectmilepost(su);
            return JsonUtil.sucessWithData("项目里程碑返回成功", AlistMilePost);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }

    //排序字段处理
    public static String humpToUnderline(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 将第一个字符处理成大写
            result.append(name.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }

    @ApiOperation(value = "/detailProjectApp", httpMethod = "GET", notes = "APP项目详情")
    @PostMapping(value = "detailProjectApp")
    @ResponseBody
    @TokenCheck
    public  JsonUtil detailProjectApp(@RequestBody ZxProjectDTO project){
        try {
            String id= project.getProjectId();
            if(StringUtils.isBlank(id)){
                return JsonUtil.error("获取参数失败");
            }
            // 查询阶段表
            JcProjectDTO jcProjectdto = getSupervisorProjectDTO(id);
            String checkShape = jcProjectdto.getCheckShape();
/*        if ("m".equals(type)) {
            //编辑 项目结束后 收回承建单位权限
            Boolean iscj = projectUnitConstructionService.isCjUser(id);
            String status = zxProjectdto.getStatus();
            if ("003".equals(status)) {
                *//*项目结束状态*//*
                if (iscj) {
                    *//*承建单位*//*
                    request.setAttribute("message", "项目已经结束，您没有权限编辑！");
                    return "/error/lcerror";
                }
            }
        }*/
            //控制按钮
//        bottonShow(request);
            /*判断是否是业主单位*/
//        Boolean isyz = projectLeaderService.isYzUser(id);
//        if (isyz) {
//            request.setAttribute("isyz", "1");
//        } else {
//            request.setAttribute("isyz", "0");
//        }
            // 查询业主单位
            // 查询业主单位
            ProjectLeaderDTO leaderdto = new ProjectLeaderDTO();
            leaderdto.setSupervisorProjectId(id);
            List<ProjectLeaderDTO> listyz = projectLeaderService.selectProjectLeaderList(leaderdto);
            // 查询项目阶段
            // 查询项目阶段
            JcProjectStageDTO dto = new JcProjectStageDTO();
            dto.setProjectId(id);
            List<JcProjectStageDTO> listStage = jcProjectStageService.selectProjectStage(dto);
            for (int i = 0; i <listStage.size() ; i++) {
                JcProjectStageDTO jcProjectStageDTO = listStage.get(i);
                String  stageId = jcProjectStageDTO.getId();
                JcProjectMilepostDTO su = new JcProjectMilepostDTO();
                su.setProjectId(id);
                su.setSupervisorProjectStageId(stageId);
                List<JcProjectMilepostDTO> AlistMilePost = jcProjectMilepostService.selectProjectmilepost(su);
                listStage.get(i).setChilds(AlistMilePost);

            }
            Boolean isProjectYc = false;
            JcProjectMilepostDTO su = new JcProjectMilepostDTO();
            su.setProjectId(id);
            List<JcProjectMilepostDTO> AlistMilePost = jcProjectMilepostService.selectProjectmilepost(su);
            // 查询付款方式
            JcProjectPayDTO payDTO = new JcProjectPayDTO();
            payDTO.setSppPrjid(id);
            List<JcProjectPayDTO> listpay = jcProjectPayService.selectSupervisorProjectPay(payDTO);

//            ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
//            pacedto.setSupProjectId(zxProjectdto.getId());
//            pacedto.setType("001");
//            List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);

            if("001".equals(jcProjectdto.getIsContinue())){
                jcProjectdto.setIsContinueName("是");
            }else{
                jcProjectdto.setIsContinueName("否");
            }

            List<ProjectBcUnit> listbc = projectBcUnitService.queryListByPro(id);

            String checkShapename = getLxText(checkShape, jcProjectdto.getProjectType());
            jcProjectdto.setCheckShapeName(checkShapename);


            HashMap  map=new HashMap();
//            map.put("palcelist", listpalce);// 签订地点
            map.put("listyz", listyz);// 业主单位
            //基本信息
            map.put("pdto", jcProjectdto);
            map.put("lclist", AlistMilePost);// 项目里程
            map.put("jdlist", listStage);// 项目阶段
            map.put("listpay", listpay);// 查询付款方式
            map.put("cjlist", listbc);// 被测单位
            return JsonUtil.sucessWithData("获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }



    public String getLxText(String field,String projectType) {
        if(StringUtil.isNotBlank(field)){
            List<BaseDict> codeList = baseDictService.selectYw(projectType);
            HashMap<String, String> mapbest = new HashMap();
            for (int i = 0; i < codeList.size(); i++) {
                mapbest.put(codeList.get(i).getBadtCode(), codeList.get(i).getBadtName());
            }
            //擅长领域
            List<String> dobest = StringUtil.split(field);
            List<String> best = new ArrayList<>();
            for (int i = 0; i < dobest.size(); i++) {
                String s = dobest.get(i);
                String scname = mapbest.get(s);
                if(StringUtil.isNotBlank(scname)){
                    best.add(scname);
                }
            }
            String strbest = best.toString().replaceAll("\\[", "").replaceAll("\\]", "");
            return strbest;

        }else{
            return "";

        }


    }
    /**
     * @param spf_prjid
     * @Description:获取SupervisorProject
     * @Author:Zhangshuo
     * @Date:11:20 2020-12-19
     */
    private JcProjectDTO getSupervisorProjectDTO(String spf_prjid) {
        JcProjectDTO jcProjectdto = new JcProjectDTO();
        //查询项目
        jcProjectdto.setId(spf_prjid);
        List<JcProjectDTO> projectlist = jcProjectService.selectJcProject(jcProjectdto);

        if (projectlist.size() > 0) {
            jcProjectdto = projectlist.get(0);
        }
        String names = "";
        String[] str = jcProjectdto.getJcAdviser().split(",");
        for (int x = 0;x<str.length;x++){
            SysUser sysUser = sysUserService.selectByPrimaryKey(str[x]);
            if(sysUser!=null){
                String name = sysUser.getRealName();
                if(x==0){
                    names = name;
                }else{
                    names = names+","+name;
                }
            }

        }
        jcProjectdto.setJcAdviserName(names);
        return jcProjectdto;
    }


    /**
     * @Author:zhaoyongke
     * @Description: 招标文件
     * @Date:10:49 2021/10/08
     */
    @ApiOperation(value = "/appMapper", httpMethod = "POST", notes = "查询阶段里程中的文件")
    @PostMapping(value = "appMapper")
    @ResponseBody
    @TokenCheck
    public JsonUtil appMapper(@RequestBody JcProjectDTO dto) {
        try {



            String id = dto.getId();
            String stageid = dto.getStageId();
            String spmid = dto.getSpmId();
            String typewj = dto.getType();
            // 查询类型  002 代表查询这个阶段下的所有文件
            String querytype = dto.getQuerytype();
            if (StringUtil.isBlank(id) || StringUtil.isBlank(stageid) ) {
                return JsonUtil.error("参数获取失败");
            }
            Map<String, Object> map = new HashMap<>();
            //查询项目
            JcProject project = jcProjectService.selectByPrimaryKey(id);
            // 查询阶段
            JcProjectStage stage = new JcProjectStage();
            stage.setId(stageid);
            stage = jcProjectStageService.selectByPrimaryKey(stage);
            if("002".equals(querytype)){
                // 查看某个阶段下的所有里程
                ArrayList  listre=new ArrayList();
                // 查询阶段下所有里程的文件
                JcProjectMilepostDTO milepost = new JcProjectMilepostDTO();
                milepost.setSupervisorProjectStageId(stageid);
                milepost.setProjectId(id);
                List<JcProjectMilepostDTO> selectMilepost = jcProjectMilepostService.selectProjectmilepost(milepost);
                // 遍历所有的里程
                for (int i = 0; i <selectMilepost.size() ; i++) {
                    ArrayList list = new ArrayList();
                    JcProjectMilepostDTO jcProjectMilepost = selectMilepost.get(i);
                    queryFilesByMile(jcProjectMilepost,typewj,id,list);
                    jcProjectMilepost.setChilds(list);
                    listre.add(jcProjectMilepost);
                }
                // 集合数据
                map.put("listdata", listre);

            }else{
                //查看单一里程
                ArrayList  listre=new ArrayList();
                // 查询某一个里程文件
                JcProjectMilepostDTO milepost = new JcProjectMilepostDTO();
                milepost.setId(spmid);
                milepost.setProjectId(id);
                List<JcProjectMilepostDTO> jcProjectMilepostDTOS = jcProjectMilepostService.selectProjectmilepost(milepost);
                JcProjectMilepostDTO jcProjectMilepostDTO = jcProjectMilepostDTOS.get(0);
                ArrayList list = new ArrayList();
                queryFilesByMile(jcProjectMilepostDTO,typewj,id,list);
                jcProjectMilepostDTO.setChilds(list);
                listre.add(jcProjectMilepostDTO);
                // 集合数据
                map.put("listdata", listre);
                map.put("lcdto", milepost);
            }
            SupervisorProjectDTO pdto = new SupervisorProjectDTO();
            BeanUtils.copyProperties(project, pdto);
            pdto.setSpmId(spmid);
            //基本信息
            map.put("pdto", pdto);
            map.put("stagedto", stage);
            return JsonUtil.sucessWithData("获取成功", map);
        } catch (BeansException e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }


    public void  queryFilesByMile(JcProjectMilepost milepost,String typewj, String id, ArrayList list){
        String milepostNo = milepost.getMilepostNo();
        BaseDict AoBaseDict = DictUtil.getDictByCode(DictTypes.PROJECT_MILEPOST_JC, milepostNo);
        String wjcode = AoBaseDict.getBadtLevel3();

        if(StringUtil.isNotBlank(typewj)){
            //只是查询检测日志
            wjcode=typewj;
        }
        if (StringUtil.isNotBlank(wjcode)) {
            String[] split = wjcode.split(",");
            for (int i = 0; i < split.length; i++) {
                String type = split[i];
                List<SupervisorFile> listjlzb = null;
                FileDTO dto1 = new FileDTO();
                if ("031".equals(type) ) {
                    //咨询付款申请 查询  需要过滤掉图片
                    Example e = new Example(SupervisorFile.class);
                    Example.Criteria c = e.createCriteria();
                    c.andEqualTo("projectId", id).andEqualTo("spmId", milepost.getId()).andEqualTo("type", type).andIsNull("parentId");
                    listjlzb = supervisorFileService.selectByExample(e);
                    if(listjlzb!=null  && listjlzb.size()>0 ){
                        for (int j = 0; j < listjlzb.size(); j++) {
                            SupervisorFile supervisorFile = listjlzb.get(j);
                            SupervisorFile filechied = new SupervisorFile();
                            filechied.setParentId(supervisorFile.getId());
                            List<SupervisorFile> select = supervisorFileService.select(filechied);
                            listjlzb.get(j).setListchilds(select);
                        }
                    }
                    dto1.setFileList(listjlzb);
                }else  if("123".equals(type)){
                    // 回款到账情况
                    JcProjectDTO jc = new JcProjectDTO();
                    jc.setId(id);
                    List<JcPayRecordDTO> jcPayRecordDTOS = jcPayRecordService.selectHk(jc);
                    if(jcPayRecordDTOS!=null  && jcPayRecordDTOS.size()>0){
                        for (int j = 0; j <jcPayRecordDTOS.size() ; j++) {
                            JcPayRecordDTO jcPayRecordDTO = jcPayRecordDTOS.get(j);
                            String arrivalDate = jcPayRecordDTO.getArrivalDate();
                            // 到账时间
                            if(StringUtils.isNotBlank(arrivalDate)){
                                String[] split1 = arrivalDate.split(",");
                                jcPayRecordDTO.setChild1(split1);
                            }
                            // 到账金额
                            String arrivalMoney = jcPayRecordDTO.getArrivalMoney();
                            if(StringUtils.isNotBlank(arrivalMoney)){
                                String[] split1 = arrivalMoney.split(",");
                                jcPayRecordDTO.setChild2(split1);
                            }
                        }

                    }
                    dto1.setFileList(jcPayRecordDTOS);
                } else {
                    SupervisorFile supervisorFile = new SupervisorFile();
                    supervisorFile.setType(type);
                    supervisorFile.setProjectId(id);
                    supervisorFile.setSpmId(milepost.getId());
                    listjlzb = supervisorFileService.select(supervisorFile);
                    dto1.setFileList(listjlzb);
                }
                //
                BaseDict AoBaseDictwj = DictUtil.getDictByCode(DictTypes.WJJC, type);
                dto1.setFileName(AoBaseDictwj.getBadtName());
                list.add(dto1);
            }
        }


    }
    /**
     * @param
     * @Author:zhaoyongke
     * @Description: 表单文件添加
     * @Date:9:29 2020/11/30
     */
    @ApiOperation(value = "/addForm", httpMethod = "POST", notes = "表单添加")
    @PostMapping(value = "addForm")
    @ResponseBody
    @TokenCheck
    public JsonUtil addForm(@RequestBody JcProjectDTO dto) throws Exception {
        try {
            String type = dto.getType();// 文件類型
            String spf_prjid = dto.getId();// 項目id
            String spf_staid = dto.getStageId();// 阶段id
            String spf_milid = dto.getSpmId();// 里程id
            String fbCode = dto.getFbCode();// 分包
            String pcId = dto.getFbId();// 分包Id
            String fileId = dto.getFileId();// 文件表id  个别form 添加是针对某个文档操作 需要知道具体是哪个文件 fileId
            String userId = dto.getUserId();
            /*承建单位不能上传监理文档*/
            if (StringUtil.isBlank(type) || StringUtil.isBlank(spf_prjid) || StringUtil.isBlank(spf_staid) || StringUtil.isBlank(userId)) {
                return JsonUtil.error("参数获取失败");
            }
//            String role = sysUserService.getUserRoleJc(spf_prjid);
//            if ("xmjl".equals(role) || "sqqzr".equals(role)  || "jcgw".equals(role)) {
//            } else {
//                return JsonUtil.error("获取权限操作");
//            }
            //查询项目详情
            //查询项目详情
            JcProjectDTO supervisorProjectdto = getSupervisorProjectDTO(spf_prjid);
            supervisorProjectdto.setFileId(fileId);
            // 获得文档流水号
            String orderCode = getFileOrderCode(spf_prjid, spf_staid, spf_milid, pcId, type);
            // 获取跳转路径
            // String re_url = getUrl(type, model);
            Map<String, Object> map = new HashMap<>();
            //特殊处理
            doSomeSpecialSthing(type, spf_prjid, fbCode, supervisorProjectdto, orderCode, userId, map);
            //解析文件数据
            //parsingFileDataToList(type, fileId, spf_prjid, pcId, map);
            // 分包数据
            //基本信息
            map.put("pdto", supervisorProjectdto);
            map.put("id", supervisorProjectdto.getId());

            map.put("stageId", spf_staid);

            map.put("spmId", spf_milid);

            map.put("ind", Integer.valueOf(orderCode));

            map.put("spfFilecode", type);// 文件类型编号

            map.put("fileId", fileId); // 文件表id
            // 返回数据
            return JsonUtil.sucessWithData("获取成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("获取失败");
        }
    }



    /**
     * @param supervisorProjectFromsDTO
     * @Author:zhaoyongke
     * @Description: 表单保存文件
     * @Date:13:06 2020/11/30
     */
    @ApiOperation(value = "/addFormFile", httpMethod = "POST", notes = "表单添加")
    @PostMapping(value = "/addFormFile")
    @ResponseBody
    @TokenCheck
    public JsonUtil addFormFile(@RequestBody SupervisorProjectFromsDTO supervisorProjectFromsDTO) {
        JsonUtil re = new JsonUtil();
        JSONObject jsonObject = new JSONObject();
        try {
            // 项目Id
            String spfPrjid = supervisorProjectFromsDTO.getSpfPrjid();
            // 文档流水编号
            Integer fileInd = supervisorProjectFromsDTO.getFileInd();
            // 阶段Id
            String spfStaid = supervisorProjectFromsDTO.getSpfStaid();
            // 里程Id
            String spfMilid = supervisorProjectFromsDTO.getSpfMilid();
            // 文件类型
            String spfFilecode = supervisorProjectFromsDTO.getSpfFilecode();

            String fbCode = supervisorProjectFromsDTO.getFbCode();

            String pcId = supervisorProjectFromsDTO.getPcId();

            String wjNum = supervisorProjectFromsDTO.getWjNum();
            // 父级Id
            String parentId = supervisorProjectFromsDTO.getFileParentId();
            // -1-014
            String orderCode = supervisorProjectFromsDTO.getOrderCode();

            String userId = supervisorProjectFromsDTO.getUserId();
            if (StringUtil.isBlank(spfPrjid) || StringUtil.isBlank(spfStaid) || StringUtil.isBlank(spfMilid)) {
                return JsonUtil.error("参数获取失败");
            }
            //文件保存路径
            String AsFilePath = prepareFormSavePath(-1, supervisorProjectFromsDTO);

            //获取Form实例
            SupervisorProjectForms AoForms = getSupervisorProjectForms(supervisorProjectFromsDTO, AsFilePath);
            AoForms.setCreateDate(DateUtil.getCurrentDateString());
            supervisorProjectFormsService.insertSelective(AoForms);
            //            //针对个别表格数据  把表格数据保存到 form-data 表中 比如 加电检验记录表
            ArrayList<SupervisorProjectFormsData> AlstFormData = supervisorProjectFromsDTO.getFormDataList();
            if (!isNull(AlstFormData)) {
                addFormData(AlstFormData, AoForms.getSpfId());
            }
            String AsLinkId = AoForms.getSpfId();
            String parent = "";
            // 查询 路径
            String templateFilePath = "";
            if ("037".equals(spfFilecode)) {
                templateFilePath = FilePathUtil.getPathConfigTemplateFile("9901");
            }
            FileInputStream in = new FileInputStream(templateFilePath);//载入文档
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in,
                    TemplateEngineKind.Freemarker);
            IContext context = report.createContext();


            if ("037".equals(spfFilecode)) {
                // 咨询日报
                // 项目名称
                context.put("projectName", supervisorProjectFromsDTO.getProjectName());
                // 人员
                context.put("ryName", supervisorProjectFromsDTO.getSpfF2());
                // 业主
                context.put("yzName", supervisorProjectFromsDTO.getSpfF3());
                // 咨询单位
                context.put("zxComName", supervisorProjectFromsDTO.getSpfF4());
                //咨询项目的主要工作
                context.put("data1", supervisorProjectFromsDTO.getSpfF5());
                //项目进度情况及分析
                context.put("data2", supervisorProjectFromsDTO.getSpfF6());
                //遗留问题及解决、风险控制情况
                context.put("data3", supervisorProjectFromsDTO.getSpfF7());
                //明日计划
                context.put("data4", supervisorProjectFromsDTO.getSpfF8());
                // 咨询工程师
                context.put("gcs", supervisorProjectFromsDTO.getSpfF9());
                // 日期
                context.put("riqidate", supervisorProjectFromsDTO.getSpfF10());
                //
                context.put("ordercode", supervisorProjectFromsDTO.getOrderCode());
            }
            // 根据模板生成文件
            createFile(report, context, AsFilePath);
            // 生成文件
            saveFile(AsFilePath, spfFilecode, spfPrjid, spfStaid, spfMilid, pcId, parentId, AsLinkId, fileInd, userId);
            // 更新状态
            if (StringUtil.isNotBlank(wjNum) && wjNum != null) {
                updateLcStatus(spfStaid, spfMilid, wjNum);
            }
            re.setFlag(true);
            re.setMsg("操作成功");
            re.setData(jsonObject);
        } catch (Exception e) {
            re.setMsg("操作失败" + e.getMessage());
            re.setFlag(false);
            e.printStackTrace();
        }
        return re;
    }

    /**
     * @param AsStageId
     * @param AsMilePostId
     * @Author:zhaoyongke
     * @Description: 修改里程 阶段状态
     * @Date:21:24 2020/12/17
     */
    public void updateLcStatus(String AsStageId, String AsMilePostId, String fs_status) {
        JcProjectMilepost supervisorProjectMilepost = jcProjectMilepostService.selectByPrimaryKey(AsMilePostId);
        String finishStatuslc = supervisorProjectMilepost.getFinishStatus();//
        String stepNum = supervisorProjectMilepost.getStepNum();
        String[] ayStatus = stepNum.split(",");
        String asPostStartIdx = fs_status.substring(0, 1);// 例如  10  20  截取  为  1 , 2
        String strsatus = ayStatus[Integer.valueOf(asPostStartIdx) - 1];
        // 该里程的状态为 进行中  或未开始 或 本文件类型为未开始的状态
        if (strsatus.substring(1, 2).equals("0") && ("0".equals(finishStatuslc) || "1".equals(finishStatuslc))) {// 判断当前文件类型的状态
            ayStatus[Integer.valueOf(asPostStartIdx) - 1] = fs_status;// 更新文件类型状态
            String str = Arrays.toString(ayStatus).replace("[", "").replace("]", "").replace(" ", "");
            supervisorProjectMilepost.setStepNum(str);
        }

        if ("0".equals(finishStatuslc)) {
            supervisorProjectMilepost.setFinishStatus("1");//进行中
        }
        /*更新里程状态*/
        jcProjectMilepostService.updateByPrimaryKey(supervisorProjectMilepost);
        /*处理阶段状态*/
        JcProjectStage stage = jcProjectStageService.selectByPrimaryKey(AsStageId);
        String finishStatusjd = stage.getFinishStatus();//
        if ("0".equals(finishStatusjd)) {
            stage.setFinishStatus("1");//进行中
            jcProjectStageService.updateByPrimaryKey(stage);
        }

    }


    /**
     * @Author:zhaoyongke
     * @Description: 针对表单存在表格得情况  插入 form-data
     * @Date:11:55 2020/12/5
     */
    public void addFormData(List<SupervisorProjectFormsData> plstFormData, String formid) {
        for (int i = 0; i < plstFormData.size(); i++) {
            SupervisorProjectFormsData formsData = plstFormData.get(i);
            formsData.setSpfId(formid);
            supervisorProjectFormsDataService.insertSelective(formsData);
        }
    }
    /**
     * @param report
     * @param context
     * @param target
     * @Author:zhaoyongke
     * @Description: 根据模板生成文件
     * @Date:10:07 2021/10/12
     */
    public void createFile(IXDocReport report, IContext context, String target) {
        try {
            //创建字段元数据
            FieldsMetadata fm = report.createFieldsMetadata();
            //Word模板中的表格数据对应的集合类型
            //fm.load("data", SupervisorProjectFormsData.class, true);
            //输出到本地目录
            FileOutputStream out = new FileOutputStream(new File(target));
            report.process(context, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XDocReportException e) {
            e.printStackTrace();
        }
    }

    public void saveFile(String pFilePath, String pFileType, String pPrjId, String pStageId, String pMilePostId, String pPkgId, String pParentId, String pLinkId, Integer fileInd,String userId) throws Exception {
        SupervisorFile countFile = new SupervisorFile();
        countFile.setProjectId(pPrjId);
        countFile.setUrl(pFilePath);
        int countfile = supervisorFileService.selectCount(countFile);
        if (countfile == 0) {
            SupervisorFile AoFile = new SupervisorFile();
            //带.的后缀名
            String AsSuffix = FilePathUtil.getFileSufiix(pFilePath);
            //获取文件名称
            String AsFileName = FilePathUtil.getFileName(pFilePath);
            // 文件名称
            AoFile.setFileName(AsFileName);
            // 文件后缀
            AoFile.setFileType(AsSuffix);
            // 文件类型
            AoFile.setType(pFileType);
            // url
            AoFile.setUrl(pFilePath);
            //項目id
            AoFile.setProjectId(pPrjId);
            //阶段id
            AoFile.setStageId(pStageId);
            //里程id
            AoFile.setSpmId(pMilePostId);
            //分包id
            AoFile.setPcId(pPkgId);
            //父级id
            AoFile.setParentId(pParentId);
            // form 表Id
            AoFile.setLinkId(pLinkId);
            AoFile.setCreateBy(userId);
            if (fileInd != null) {
                AoFile.setInd(fileInd);
            }
            if (!"112".equals(pFileType)) {
                projectBigEventService.saveProejctBigEventJcApp(pPrjId, pMilePostId, pStageId, userId);
            }
            supervisorFileService.insertSelective(AoFile);
        }
        //材料设备进场检验报告

    }

    /**
     * @param poSupervisorProjectFromsDTO
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:29 2020/12/4
     */
    private String prepareFormSavePath(int piFileCount, SupervisorProjectFromsDTO poSupervisorProjectFromsDTO) {
        // 准备上传参数
        String AsPrjName = poSupervisorProjectFromsDTO.getProjectName();
        String AsFileType = poSupervisorProjectFromsDTO.getSpfFilecode();
        String AsFbCode = poSupervisorProjectFromsDTO.getFbCode();
        String AsFpId = poSupervisorProjectFromsDTO.getBfcId();
        SupervisorFile AoSupervisorFile = getSupervisorFile(poSupervisorProjectFromsDTO);
        AoSupervisorFile.setType(AsFileType);

        String AsFileStuffix = ".doc";
        UploadType uploadType = prepareUploadType(0, AsPrjName, AsFileType, AsFbCode, AsFpId, AsFileStuffix, piFileCount, AoSupervisorFile, "", "");
        poSupervisorProjectFromsDTO.setFileInd(uploadType.getInd());
        String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
        return AsFilePath;
    }

    /**
     * @param type             上传类型 UploadType EnumByType
     * @param psPrjName        项目名称
     * @param psFileType       文件类型
     * @param psFbCode         分包编号
     * @param psFpId           路径配置表ID
     * @param poSupervisorFile
     * @Author:Zhangshuo
     * @Description:获取上传UploadType
     * @Date:10:03 2020/12/4
     */
    public UploadType prepareUploadType(int type, String psPrjName, String psFileType, String psFbCode, String psFpId, String psFileStuffix, int piFileCount, SupervisorFile poSupervisorFile, String pUploadType, String pPositionName) {
        // 获取文件名称
        String AsFileName = FileUtils.getFileNameJc(psPrjName, psFileType, psFbCode, psFileStuffix, piFileCount, poSupervisorFile, pUploadType, pPositionName);
        // 替换项目名称
        ArrayList<String> placeHolder = new ArrayList<String>();
        placeHolder.add(psPrjName);
        placeHolder.add(psFbCode);
        placeHolder.add(pPositionName);
        UploadType uploadType = UploadType.getEnumByType(type);
        uploadType.setFileName(AsFileName);
        uploadType.setFilePathId(psFpId);
        uploadType.setPlaceholder(placeHolder);
        uploadType.setInd(poSupervisorFile.getInd());
        return uploadType;
    }

    /**
     * @param supervisorProjectFromsDTO
     * @param psFilePath
     * @Author:Zhangshuo
     * @Description:
     * @Date:10:20 2020/12/4
     */
    private SupervisorProjectForms getSupervisorProjectForms(SupervisorProjectFromsDTO supervisorProjectFromsDTO, String psFilePath) {
        SupervisorProjectForms form = new SupervisorProjectForms();
        BeanUtil.copyNotNullBean(supervisorProjectFromsDTO, form);
        form.setSaveFilePath(psFilePath);
        form.setSpfId(IdUtil.simpleUUID());
        return form;
    }

    /**
     * @param poSupervisorProjectFromsDTO
     * @Author:Zhangshuo
     * @Description:
     * @Date:9:31 2020/12/4
     */
    private SupervisorFile getSupervisorFile(SupervisorProjectFromsDTO poSupervisorProjectFromsDTO) {
        SupervisorFile file = new SupervisorFile();
        file.setProjectId(poSupervisorProjectFromsDTO.getSpfPrjid());
        file.setStageId(poSupervisorProjectFromsDTO.getSpfStaid());
        file.setSpmId(poSupervisorProjectFromsDTO.getSpfMilid());
        if (StringUtil.isNotBlank(poSupervisorProjectFromsDTO.getPcId())) {
            file.setPcId(poSupervisorProjectFromsDTO.getPcId());
        }
        return file;
    }

    private void doSomeSpecialSthing(String type, String spf_prjid, String fbCode, JcProjectDTO supervisorProjectdto, String orderCode, String userId, Map<String, Object> mapdata) {

        ProjectUnitConstructionDTO unitConstructiondto = new ProjectUnitConstructionDTO();
        unitConstructiondto.setSupervisorProjectId(spf_prjid);
        if ("039".equals(type)) {
            /*材料进场检验报告*/
            unitConstructiondto.setConstructionSubContractNumber(fbCode);
        }

        if (com.qili.core.shiro.Principal.hasRole("nupm")) {
            //承建单位
            unitConstructiondto.setProjectManager(CommonUtil.getUserId());
        }
        if ("111".equals(type)) {
            /*监理通知回执单 需要查询监理通知选择的承建单位*/
            String fileId = supervisorProjectdto.getFileId();
            SupervisorFile fileparent = supervisorFileService.selectByPrimaryKey(fileId);
            String linkId = fileparent.getLinkId() + "";
            if (StringUtil.isNotBlank(linkId)) {
                SupervisorProjectForms form = supervisorProjectFormsService.selectByPrimaryKey(linkId);
                /*承建单位项目经理*/
                String cjManagerUserId = form.getSpfF30() + "";
                if (StringUtil.isNotBlank(cjManagerUserId)) {
                    unitConstructiondto.setProjectManager(cjManagerUserId);
                }
                String parentordercode = "JLTZ-" + form.getOrderCode();
                // model.addAttribute("parentordercode", parentordercode);
            }


        }
        List<ProjectUnitConstructionDTO> listcjlist = projectUnitConstructionService.selectProjectUnitList(unitConstructiondto);
        //承建单位名称
        ArrayList<String> AlstCjdwstr = new ArrayList<>();
        //承建合同名称
        ArrayList<String> AlstCjHtstr = new ArrayList<>();
        for (int i = 0; i < listcjlist.size(); i++) {
            AlstCjdwstr.add(listcjlist.get(i).getUnitConstruction());
            // 承建合同名称
            AlstCjHtstr.add(listcjlist.get(i).getConstructionContract());
        }
        String cj = AlstCjdwstr.toString();
        String cjstr = "";
        if (StringUtil.isNotBlank(cj)) {
            //截取前后【】
            cjstr = cj.replaceAll("\\[", "").replaceAll("\\]", "");
        }
        String cjht = AlstCjHtstr.toString();
        String cjhtstr = "";
        if (StringUtil.isNotBlank(cjht)) {
            //截取前后【】
            cjhtstr = cjht.replaceAll("\\[", "").replaceAll("\\]", "");
        }
        mapdata.put("cj", cjstr);
        mapdata.put("cjht", cjhtstr);
        if ("080".equals(type) || "060".equals(type) || "054".equals(type)) {
            // 监理 工作总结报告  查询统计文档列表
//            getFileTypeCountList(model, spf_prjid);
//            //获取项目分包及建设内容
//            getProjectUnitInfor(model, supervisorProjectdto, listcjlist);
        }
        if (type.equals("039")) {
            /*材料设备进场检验报告*/
            orderCode = "-" + fbCode + "-" + orderCode;
        } else if (type.equals("040") || type.equals("041")) {
            /*设备开箱检验报告 设备加电检测记录表*/
            //获取材料进场检验报告的序号
            String fileId = supervisorProjectdto.getFileId();
            SupervisorFile file = supervisorFileService.selectByPrimaryKey(fileId);
            String lnkid = file.getLinkId();
            SupervisorProjectForms from = supervisorProjectFormsService.selectByPrimaryKey(lnkid);
            orderCode = from.getOrderCode();
        }
        // 文件类型编号

        mapdata.put("orderCode", orderCode);
        mapdata.put("listcjlist", listcjlist);



    }
    /**
     * @param spf_prjid 项目ID
     * @param spf_milid 里程ID
     * @param fbid      分包ID
     * @param psType    文件类型
     * @Author:Zhangshuo
     * @Description:
     * @Date:12:25 2020/12/4
     */
    public String getFileOrderCode(String spf_prjid, String spf_staid, String spf_milid, String fbid, String psType) {
        SupervisorFile AoSupervisorFile = new SupervisorFile();
        AoSupervisorFile.setProjectId(spf_prjid);
        AoSupervisorFile.setStageId(spf_staid);
        AoSupervisorFile.setSpmId(spf_milid);
        AoSupervisorFile.setType(psType);
        if (StringUtil.isNotBlank(fbid)) {
            AoSupervisorFile.setPcId(fbid);
        }
        Integer count = 0;
        Map paraMap = new HashMap<>();
        paraMap.put("projectId", AoSupervisorFile.getProjectId());
        if ("055".equals(psType) || "061".equals(psType) || "081".equals(psType)) {
            // 特殊处理：初验： 055 验收报告 终验：061验收报告 验收阶段：081 验收报告 三种文档整体按顺序排列
            List<String> typeList = new ArrayList<String>();
            typeList.add("055");
            typeList.add("061");
            typeList.add("081");
            paraMap.put("typeList", typeList);
        } else if ("036".equals(psType) || "037".equals(psType)) {
            // 特殊处理：
            List<String> typeList = new ArrayList<String>();
            typeList.add("036");
            typeList.add("037");
            paraMap.put("type", AoSupervisorFile.getType());
        } else {
            if (StringUtils.isNotBlank(AoSupervisorFile.getPcId())) {
                paraMap.put("pcId", AoSupervisorFile.getPcId());
            }
            if (StringUtils.isNotBlank(AoSupervisorFile.getSpmId())) {
                paraMap.put("spmId", AoSupervisorFile.getSpmId());
            }
            paraMap.put("type", AoSupervisorFile.getType());
        }
        count = supervisorFileService.selectMaxOrderBySupervisorFile(paraMap) + 1;
        NumberFormat formatter = new DecimalFormat("000");
        String AsOrderNum = formatter.format(count);
        return AsOrderNum;
    }




}
